<?php
class DisQueue
{
	private $host;
	private $client;
	private $lasttime;
	private $state;
	private $laststate;
	private $persistent;
	
	public function __construct($host, $persistent=false)
	{
		$this->host = $host;
		$this->state = 'master';
		$this->persistent = $persistent;
		$this->client = NULL;
	}

	public function connect()
	{
		if(!$this->client )
		{
			$this->client = new Predis_Client($this->host[$this->state]);
			return $this->connect();
		}
		else if(!$this->client->isConnected())
		{
			$this->client->disconnect();
			$this->client->connect();
		}
		else
		{
			
		}
		
		$ret = $this->client->isConnected();
		if(!$ret)
		{
			if($this->state == $this->laststate)
			{
				//$this->disConnect();
				//$this->state = $this->state == "master" ? 'slave' : 'master';
				//return $this->connect();
			}
			else 
			{
			
				throw new Predis_ClientException(
	                'Cannot connet the predis queue server'
	            );
			}
		}
		else
		{
			$this->laststate = $this->state;
		}
		
		return $ret;
	}
	
	public function disConnect()
	{
		$this->client->disconnect();
		$this->client = NULL;
	}
	
	public function get($name)
	{
		$this->connect();
		$ret = $this->client->lpop($name);
		
		if(!$this->persistent)
		{
			$this->disConnect();
		}
		
		return $ret ? $ret : false;
	}
	
	public function put($name, &$data)
	{
		$this->connect();
		$ret = $this->client->rpush($name,$data);
		if(!$this->persistent)
		{
			$this->disConnect();
		}
		
		return $ret ? true : false;
	}
	
	
};
